package com.lzh.others.basejava.Thread_21;

import java.util.concurrent.TimeUnit;

/**
 * @Classname DaemonsDontRunFinally
 * @Description 后台线程哎不执行finally子句的情况下会终止其run()方法
 * 当main线程退出后，会直接终止所有的后台线程，因此，不能优雅的关闭后台线程。
 * //TODO  非后台的Executor是更好的解决方式，为什么呢？
 * @Date 2021/9/15 11:05
 * @Created by liuzihao
 */
class ADaemon implements Runnable {

    @Override
    public void run() {
        try {
            System.out.println("Starting ADaemon");
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("Exiting via InterruptedException");
        } finally {
            System.out.println("This should always run?");
        }
    }
}

public class DaemonsDontRunFinally {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new ADaemon());
        thread.setDaemon(true);
        thread.start();
        TimeUnit.SECONDS.sleep(2);
    }
}
